//
//  YKXMPPTool.m
//  WeChat
//
//  Created by 吴高烽 on 16/5/22.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKXMPPTool.h"
@interface YKXMPPTool ()<XMPPStreamDelegate>{
    XMPPResultBlock _resultBlock;/// 回调用的block
    XMPPvCardTempModule *_vCard ; // 电子名片模块
    XMPPvCardCoreDataStorage *_vCardStorage ; // 电子名片数据存储
//    XMPPRoster *_roster;// 花名册模块
//    XMPPRosterCoreDataStorage *_rosterStorage;//花名册的数据存储
    XMPPReconnect *_reconnect ;
}
@property (nonatomic ,assign,getter=isRegisterUser)BOOL registerUser;
/**
 *   1、初始化xmppStream
 */
-(void)setupStream;
/**
 *   2、连接服务器 传jid
 */
-(void)connectToHost;
/**
 *   3、连接成功发送密码
 */
-(void)sendPwdToHost;
/**
 *  发送一个“在线”状态给服务器
 */
-(void)sendOnlineMessage;
/**
    5. 取消模块，释放资源
 */
-(void)teardownStream;

@end

@implementation YKXMPPTool
singleton_implementation(YKXMPPTool)
#pragma mark -私有方法
// 初始化stream
-(void)setupStream{
    //     初始化对象
    _xmppStream =[[XMPPStream alloc]init];
    
//    添加xmpp的模块  电子名片
    _vCardStorage =[XMPPvCardCoreDataStorage sharedInstance];
    _vCard =[[XMPPvCardTempModule alloc]initWithvCardStorage:_vCardStorage];
    [_vCard activate:_xmppStream]; //激活电子名片模块
    
//    电子名片模块还会配合头像模块使用
    _avatar =[[XMPPvCardAvatarModule alloc]initWithvCardTempModule:_vCard];
    [_avatar activate:_xmppStream];
    
//     3、添加“花名册”模块
    _rosterStorage = [[XMPPRosterCoreDataStorage alloc]init];
    _roster = [[XMPPRoster alloc]initWithRosterStorage:_rosterStorage];
    [_roster activate:_xmppStream];  //!> 激活花名册
//    4.添加消息模块
    _msgArchStorge = [[XMPPMessageArchivingCoreDataStorage alloc]init];
    _msgArchiving = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:_msgArchStorge];
    [_msgArchiving activate:_xmppStream];
//    5. 自动连接模块
    _reconnect = [[XMPPReconnect alloc]init];
    [_reconnect activate:_xmppStream];
    //    设置代理
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}
-(void)teardownStream{
//    移除代理
    [_xmppStream removeDelegate:self];

//    取消模块
    [_avatar deactivate];
    [_vCard deactivate];
    [_roster deactivate];
    [_reconnect deactivate];
//    断开连接
    [_xmppStream disconnect];
    
//    清空资源
    _roster = nil ;
    _rosterStorage = nil ;
    _vCardStorage = nil;
    _vCard = nil;
    _avatar = nil ;
    _msgArchiving = nil;
    _msgArchStorge = nil ;
    _reconnect = nil;
    _xmppStream = nil ;

}
//连接服务器，传递一个id
-(void)connectToHost{
    if (!_xmppStream) {
        [self setupStream];
    }
    //    1.设置登录用户的id
    // jidWithUser:用户名     domain：  resource：设备类型
    YKAccount *accout =[YKAccount shareAccount];
    NSString *user;
    if (self.isRegisterUser) {//register
        user =accout.registerUser;
    }else{//login
       user=accout.loginUser;
    }
    XMPPJID *myJID=[XMPPJID jidWithUser:user domain:accout.domain resource:nil];
    YKLog(@"myjid=%@",myJID);
    _xmppStream.myJID =myJID;
    //    2.设置主机地址
    _xmppStream.hostName=accout.host;
//    accout.host;
    //    3.设置主机端口
    _xmppStream.hostPort = accout.port;
    //    4.发起连接
    NSError *err;
    //    缺少必要的参数时会发起连接失败
    [_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&err];
    if (err) {
       YKLog(@"%@",err);
    } else {
        YKLog(@"发起连接成功");
    }
}
// 连接成功发送密码
-(void)sendPwdToHost{
    NSError *err = nil ;
    NSString *psw = [YKAccount shareAccount].loginPwd ;
    [_xmppStream authenticateWithPassword:psw error:&err];
    if (err) {
        YKLog(@"发送密码失败-%@",err);
    }
}
//发送在线状态
-(void)sendOnlineMessage{
    //     xmpp已经把所有的指令封装成对象了
    XMPPPresence *presence=[XMPPPresence presence];
    YKLog(@"在线状态-%@",presence);
    [_xmppStream sendElement:presence];
}
//发送离线消息
-(void)sendOfflineMessage{
    XMPPPresence *offline=[XMPPPresence presenceWithType:@"unavailable"];
    [_xmppStream sendElement:offline];
}
// 与主机断开连接
-(void)disconnetToHost{
    [_xmppStream disconnect];
}
#pragma mark -XMPPDelegate
#pragma mark -XMPP连接建立成功
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
//    NSLog(@"%s",__func__);
    if (self.isRegisterUser) {
        NSError *error;
        NSString *registerPwd =[YKAccount shareAccount].registerPwd;
        [_xmppStream registerWithPassword:registerPwd error:&error];
    }else{
        //    回掉block
        [self sendPwdToHost];
    }

}
#pragma mark -XMPP断开连接
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
    YKLog(@"XMPP断开连接-%@",error);
}

#pragma mark -授权/登录成功
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    YKLog(@"登录成功");
    [self sendOnlineMessage];
    if (_resultBlock) {
        _resultBlock(XMPPResultTyepLoginSuccess);
    }
}
#pragma mark -登录失败
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
    YKLog(@"登录失败 - %@",error);
    if (_resultBlock) {
        _resultBlock(XMPPResultTyepLoginFailure);
    }
    
}
#pragma mark -注册成功
-(void)xmppStreamDidRegister:(XMPPStream *)sender{
    if (_resultBlock) {
        self.registerUser = NO;
        _resultBlock(XMPPResultTyepRegisterSuccess);
    }
}
-(void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error{
    YKLog(@"没有注册-%@",error);
    if (_resultBlock) {
        _resultBlock(XMPPResultTyepRegisterFailure);
    }
    
}
#pragma mark -注册失败
#pragma mark -公共方法
/**
 *  用户登录
 */
-(void)xmppLogin:(XMPPResultBlock)resultBlock{
    //    保存block
    [self disconnetToHost];
    _resultBlock = resultBlock;
    [self connectToHost];
    
}
-(void)xmppLogout{
    [self sendOfflineMessage];
    [self disconnetToHost];
}
-(void)xmppRegister:(XMPPResultBlock)resultBlock{
    [_xmppStream disconnect];
    self.registerUser = YES;
    _resultBlock=resultBlock;
    [self connectToHost];
    
}

-(void)dealloc{
    [self teardownStream];
}
@end
